package cn.edu.zzuli.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class CurrentUserInterceptor implements HandlerInterceptor {

    //在一个线程内可以共享的数据。
    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");

        //直接放行，我们并不在这里做鉴权
        if (authorization == null) {
            return true;
        }

        String[] s = authorization.split(" ");

        if (s.length == 2) {
            String token = s[1];
            try {
//                Map<String, Object> jsonFromToken =
//                        JwtUtils.getJsonFromToken(token);
//                Long uId = Long.parseLong((String)jsonFromToken.get("uId"));

                //我们把 uId放入到 threadLocal 达到共享的目的
//                threadLocal.set(uId);
            } catch (Exception e) {
                log.error("token 校验失败");
                return false;
            }

        }

        return true;
    }
}
